package com.zhsj.OkeHomeConsumption.ui.activity.wallet;

import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.FormalUserInfo;
import com.zhsj.OkeHomeConsumption.network.HttpClient;
import com.zhsj.OkeHomeConsumption.network.JsonResponseHandler;
import com.zhsj.OkeHomeConsumption.other.TimeChecker;
import com.zhsj.OkeHomeConsumption.other.URLEntity;
import com.zhsj.OkeHomeConsumption.utils.JsonUtils;
import com.zhsj.OkeHomeConsumption.utils.LogUtils;
import com.zhsj.OkeHomeConsumption.utils.ParamMatchUtils;
import com.zhsj.OkeHomeConsumption.utils.SignUtil;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by zwj on 2017/10/15.
 * 添加银行卡
 */

public class AddBankFragment extends BaseFragment implements View.OnClickListener{

    /**
     * 计时器
     */
    private TimeChecker timeChecker = null;
    /**
     * 实例化ProgressDrawableAlertDialog
     */
    private ProgressDrawableAlertDialog pDialogUtils = null;
    //左标提
    private TextView topbar_textview_leftitle;
    //标题
    private TextView topbar_textview_title;
    //银行卡号
    private ClearEditText mBankNo;
    //预留手机号
    private ClearEditText mPhone;
    //验证码
    private ClearEditText mCode;
    //发送验证码
    private TextView mSend;
    private SendSmsCodeCount mSendSmsCodeCount;
    //添加
    private TextView addBank;
    private String mToken;

    private FormalUserInfo userInfo;
    public static AddBankFragment newInstance(FormalUserInfo userInfo) {
        
        Bundle args = new Bundle();
        AddBankFragment fragment = new AddBankFragment();
        args.putSerializable("userInfo",userInfo);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        userInfo = (FormalUserInfo) getArguments().getSerializable("userInfo");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_addbank, container, false);
        initView(view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initListener();
    }

    private void initView(View view){
        topbar_textview_leftitle = (TextView) view.findViewById(R.id.topbar_textview_leftitle);
        topbar_textview_leftitle.setVisibility(View.VISIBLE);
        topbar_textview_title = (TextView) view.findViewById(R.id.topbar_textview_title);
        topbar_textview_title.setText("开通钱包");
        mBankNo = (ClearEditText) view.findViewById(R.id.bankno_edit);
        mPhone = (ClearEditText) view.findViewById(R.id.phone_edit);
        mCode = (ClearEditText) view.findViewById(R.id.code_edit);
        mSend = (TextView) view.findViewById(R.id.send);
        addBank = (TextView) view.findViewById(R.id.add_text);
    }

    private void initListener(){
        timeChecker = new TimeChecker(TimeOutHandler.timeOutHandler, Constants.TIME_OUT);
        pDialogUtils = new ProgressDrawableAlertDialog(_mActivity);
        topbar_textview_leftitle.setOnClickListener(this);
        mSend.setOnClickListener(this);
        addBank.setOnClickListener(this);
        mSendSmsCodeCount = new SendSmsCodeCount(60 * 1000, 100);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.topbar_textview_leftitle:
                _mActivity.onBackPressed();
                break;
            case R.id.send:
                //发送验证码
                check(mPhone.getText().toString().trim());
                if (TextUtils.isEmpty(mBankNo.getText().toString().trim())){
                    showShortToast("请填写银行卡号");
                    return;
                }
                //13521444934
                sendCode("RSA",userInfo.getId() + "", SubmitCaseContent(), mBankNo.getText().toString().trim(), mPhone.getText().toString().trim(), "D");
                break;
            case R.id.add_text:
                //添加
                if (TextUtils.isEmpty(mCode.getText().toString().trim())){
                    showShortToast("请填写验证码");
                    return;
                }
                addBank("RSA",userInfo.getId() + "", mCode.getText().toString().trim(), mToken);
                break;
        }
    }

    private List<HashMap<String, String>> hashMapLists;
    /**
     * 风控参数
     * @return
     */
    public String SubmitCaseContent() {
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String content = "";
        if (hashMapLists == null)
            hashMapLists = new ArrayList<>();
        if (hashMapLists.size() > 0)
            hashMapLists.clear();

        HashMap<String, String> map = new HashMap<>();
        map.put("user_info_dt_register",df.format(new Date()));

        hashMapLists.add(map);

        if (hashMapLists == null) {
            return "";
        }
        StringBuilder mStringBuilder = new StringBuilder();

        for (int i = 0; i < hashMapLists.size(); i++) {
            String hashMapToJson = JsonUtils.hashMapToJson(hashMapLists.get(i));
            mStringBuilder.append(hashMapToJson).append(",");
        }
        if (mStringBuilder.length() > 0) {
            String substring = mStringBuilder.toString().substring(0, mStringBuilder.toString().lastIndexOf(","));
            content = substring;
        } else {
//            showShortToast("供应信息不能为空");
        }
        return content;
    }

    /**
     * 绑定银行卡获取手机验证码
     * @param sign_type RSA
     * @param user_id 用户id
     * @param risk_item 风控参数
     * @param card_no 银行卡账号
     * @param bind_mob 绑定手机号
     */
    public void sendCode(String sign_type, String user_id, String risk_item, String card_no, String bind_mob, String pay_type) {
        mSendSmsCodeCount.start();
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        HashMap<String, String> mSendCodeHashMap = new HashMap<String, String>();
//        mSendCodeHashMap.put("token", Constants.TOKEN);
        mSendCodeHashMap.put("v", Constants.APPVERSION);
        mSendCodeHashMap.put("t", Constants.TIME);
        mSendCodeHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mSendCodeHashMap.put("platform", Constants.PLAFORM);
        mSendCodeHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mSendCodeHashMap.put("client", Constants.CLIENT);
        mSendCodeHashMap.put("sign_type", sign_type);
        mSendCodeHashMap.put("user_id", user_id);
        mSendCodeHashMap.put("risk_item", risk_item);
        mSendCodeHashMap.put("card_no", card_no);
        mSendCodeHashMap.put("bind_mob", bind_mob);
        mSendCodeHashMap.put("pay_type", pay_type);

        LogUtils.e("mSendCodeHashMap", mSendCodeHashMap.toString());
        //post 传参
        paramMaps.put("sign_type", sign_type);
        paramMaps.put("user_id", user_id);
        paramMaps.put("risk_item", risk_item);
        paramMaps.put("card_no", card_no);
        paramMaps.put("bind_mob", bind_mob);
        paramMaps.put("pay_type", pay_type);

        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mSendCodeHashMap);
        LogUtils.e("mSendCodeHashMap", SignUtil.getInstance().getSign(mSendCodeHashMap));
        HttpClient.post(OkeHomeConsumptionApi.WALLET_BANK_PHONE_CODE, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
                    LogUtils.e("content_钱包绑定银行卡获取手机验证码", "content=" + content);
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        // 数据对接正常
                        JSONObject jsonObject = jsonOBJ.optJSONObject("data");
                        JSONObject data = jsonObject.optJSONObject("data");
                        String ret_msg = data.optString("ret_msg");
                        String ret_code = data.optString("ret_code");
                        if ("0000".equals(ret_code)) {
                            mToken = data.optString("token");
                        }else {
                            showShortToast(ret_msg + "");
                        }


                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    } else {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    }
                } catch (Exception ex) {
                    LogUtils.e("DresserPartnerRegisterPost", "失败 ");
                }
            }

            @Override
            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });
    }

    /**
     * 绑定银行卡获取手机验证码
     * @param sign_type RSA
     * @param user_id 用户id
     * @param verify_code 验证码
     */
    public void addBank(String sign_type, String user_id, String verify_code, String token) {
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        HashMap<String, String> mSendCodeHashMap = new HashMap<String, String>();
//        mSendCodeHashMap.put("token", Constants.TOKEN);
        mSendCodeHashMap.put("v", Constants.APPVERSION);
        mSendCodeHashMap.put("t", Constants.TIME);
        mSendCodeHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mSendCodeHashMap.put("platform", Constants.PLAFORM);
        mSendCodeHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mSendCodeHashMap.put("client", Constants.CLIENT);
        mSendCodeHashMap.put("sign_type", sign_type);
        mSendCodeHashMap.put("user_id", user_id);
        mSendCodeHashMap.put("verify_code", verify_code);
        mSendCodeHashMap.put("token", token);

        LogUtils.e("mSendCodeHashMap", mSendCodeHashMap.toString());
        //post 传参
        paramMaps.put("sign_type", sign_type);
        paramMaps.put("user_id", user_id);
        paramMaps.put("verify_code", verify_code);
        paramMaps.put("token", token);

        // 网络计时器及线程
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mSendCodeHashMap);
        LogUtils.e("mSendCodeHashMap", SignUtil.getInstance().getSign(mSendCodeHashMap));
        HttpClient.post(OkeHomeConsumptionApi.WALLET_BANK_PHONE_CODE_ISOK, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                TimeOutHandler.pDialogUtils = null;
                try {
                    LogUtils.e("content_钱包绑定银行卡验证码验证", "content=" + content);
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        // 数据对接正常
                        JSONObject jsonObject = jsonOBJ.optJSONObject("data");
                        JSONObject data = jsonObject.optJSONObject("data");
                        String ret_msg = data.optString("ret_msg");
                        String ret_code = data.optString("ret_code");
                        if ("0000".equals(ret_code)) {
                            showShortToast("成功绑定银行卡");
                            setFragmentResult(RESULT_OK, new Bundle());
                            _mActivity.onBackPressed();
                        }else {
                            showShortToast(ret_msg + "");
                        }

                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    } else {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    }
                } catch (Exception ex) {
                    LogUtils.e("DresserPartnerRegisterPost", "失败 ");
                }
            }

            @Override
            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });
    }


    /**
     * 检测手机号
     * @param phone
     * @return
     */
    private boolean check(String phone) {
        if (TextUtils.isEmpty(phone)) {
            showShortToast("请填写手机号");
            return false;
        }

        if (!ParamMatchUtils.isPhoneAvailable(phone)) {
            showShortToast("请填写正确的手机号");
            return false;
        }
        return true;
    }

    class SendSmsCodeCount extends CountDownTimer {

        public SendSmsCodeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            mSend.setEnabled(true);
            mSend.setTextColor(Color.parseColor("#79AB1C"));
            mSend.setGravity(Gravity.CENTER);
            mSend.setTextSize(14);
            mSend.setText("发送");
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mSend.setEnabled(false);
            if (millisUntilFinished / 1000 == 0) {
                onFinish();
            } else {
                mSend.setText(millisUntilFinished / 1000 + "");
                mSend.setTextColor(Color.parseColor("#B2B2B2"));
                mSend.setGravity(Gravity.CENTER);
                mSend.setTextSize(14);
            }
        }
    }
}
